<template>
    <div>
        <Category :scene="scene" />
        <el-card style="margin-top: 0.625rem;">
            <div v-show="scene == 0">
                <el-button type="primary" size="default" icon="Plus" @click="addAttr"
                    :disabled="categoryStore.c3Id ? false : true" v-has="`btn.Attr.add`">添加属性</el-button>
                <el-table border style="margin-top: 0.625rem;" :data="attrArr">
                    <el-table-column label="序号" type="index" align="center" width="80px"></el-table-column>
                    <el-table-column label="属性名称" width="120px" prop="attrName"></el-table-column>
                    <el-table-column label="属性值名称">
                        <template #="{ row, $index }">
                            <el-tag style="margin: .375rem;" v-for="(item, index) in row.attrValueList"
                                :key="item.id">{{ item.valueName }}</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="120px">
                        <template #="{ row, $index }">
                            <el-button type="primary" size="small" icon="Edit" @click="updateAttr(row)" title="修改属性"
                                v-has="`btn.Attr.update`"></el-button>
                            <el-popconfirm :title="`您确定删除${row.attrName}吗？`" width="12rem" icon="Delete"
                                @confirm='removeAttr(row.id)'>
                                <template #reference>
                                    <el-button type="primary" size="small" icon="Delete" title="删除属性"
                                        v-has="`btn.Attr.remove`"></el-button>
                                </template>
                            </el-popconfirm>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div v-show="scene == 1">
                <!--展示添加与修改属性的结构-->
                <el-form :inline="true">
                    <el-form-item label="属性名称">
                        <el-input placeholder="请输入属性名称" v-model="attrParams.attrName"></el-input>
                    </el-form-item>
                </el-form>
                <el-button type="primary" size="default" icon="Plus" @click="addAttrValue"
                    :disabled="attrParams.attrName ? false : true">添加属性值</el-button>
                <el-button type="primary" size="default" @click="cancel">取消</el-button>
                <el-table border style="margin: 0.625rem 0;" :data="attrParams.attrValueList">
                    <el-table-column label="序号" type="index" align="center" width="80px"></el-table-column>
                    <el-table-column label="属性值名称" width="240px">
                        <!--row：当前属性值对象-->
                        <template #="{ row, $index }">
                            <el-input placeholder="请输入属性值名称" v-model="row.valueName" v-if="row.flag"
                                :ref="(vc: any) => inputArr[$index] = vc" @blur="toLook(row, $index)"></el-input>
                            <div v-else @click="toEdit(row, $index)">{{ row.valueName }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column label="属性值操作">
                        <template #="{ row, $index }">
                            <el-button type="primary" size="small" icon="Delete"
                                @click="attrParams.attrValueList.splice($index, 1)"></el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <el-button type="primary" size="default" @click="save"
                    :disabled="attrParams.attrValueList.length > 0 ? false : true">保存</el-button>
                <el-button type="primary" size="default" @click="cancel">取消</el-button>
            </div>
        </el-card>
    </div>
</template>

<script setup lang="ts">
//获取分类的仓库
import useCategoryStore from '@/store/modules/category'
import { watch, ref, reactive, nextTick, onBeforeUnmount } from 'vue'
//引入获取已有属性与属性值接口
import { reqAttr, reqAddOrUpdateAttr, reqDeleteAttr } from '@/api/product/attr'
import type { AttrResponseData, Attr, AttrValue } from '@/api/product/attr/type'
import { ElMessage } from 'element-plus';

let categoryStore = useCategoryStore()
//存储已有的属性与属性值
let attrArr = ref<Attr[]>([])
//定义card组件内容切换变量
let scene = ref<number>(0)
//收集新增属性的数据
let attrParams = reactive<Attr>({
    attrName: '',
    attrValueList: [],
    categoryId: '',
    categoryLevel: 3
})
//准备一个数组将来存储el-input实例
let inputArr = ref<any>([])

//获取已有的属性和属性值方法
const getAttr = async () => {
    //获取分类的id
    const { c1Id, c2Id, c3Id } = categoryStore
    let result: AttrResponseData = await reqAttr(c1Id, c2Id, c3Id)
    if (result.code == 200) {
        attrArr.value = result.data
    }
}
//添加属性按钮的回调
const addAttr = () => {
    //每一次点击先清空数据
    Object.assign(attrParams, {
        attrName: '',
        attrValueList: [],
        categoryId: categoryStore.c3Id,
        categoryLevel: 3
    })
    //切换为添加与修改属性的结构
    scene.value = 1
}
//修改属性按钮的回调
const updateAttr = (row: Attr) => {
    //切换为添加与修改属性的结构
    scene.value = 1
    //将已有属性对象赋值给attrParams对象
    Object.assign(attrParams, JSON.parse(JSON.stringify(row)))
}
//取消按钮的回调
const cancel = () => {
    //切换为属性展示结构
    scene.value = 0
}
//添加属性值按钮的回调
const addAttrValue = () => {
    //点击添加属性值按钮的时候，向数组添加一个属性值对象
    attrParams.attrValueList.push({
        valueName: '',
        flag: true  //控制编辑模式与查看模式的切换
    })
    //获取最后的el-input实例对象
    nextTick(() => {
        inputArr.value[attrParams.attrValueList.length - 1].focus()
    })
}
//保存按钮的回调
const save = async () => {
    //发请求
    let result: any = await reqAddOrUpdateAttr(attrParams)
    if (result.code == 200) {
        //切换场景
        scene.value = 0
        //提示信息
        ElMessage({
            type: 'success',
            message: attrParams.id ? '修改成功' : '添加成功'
        })
        //获取已有的全部属性与属性值
        getAttr()
    } else {
        //提示信息
        ElMessage({
            type: 'error',
            message: attrParams.id ? '修改失败' : '添加失败'
        })
    }
}
//属性值表单元素失去焦点的方法
const toLook = (row: AttrValue, $index: number) => {
    //非法情况1判断：不能为空
    if (row.valueName.trim() == '') {
        //删除空项
        attrParams.attrValueList.splice($index, 1)
        ElMessage({
            type: 'error',
            message: '属性值不能为空'
        })
        return
    }
    //非法情况2判断：不能重复
    let repeat = attrParams.attrValueList.find((item) => {
        if (item != row) {
            return item.valueName === row.valueName
        }
    })
    if (repeat) {
        //删除重复项
        attrParams.attrValueList.splice($index, 1)
        ElMessage({
            type: 'error',
            message: '属性值不能重复'
        })
        return
    }
    row.flag = false
}
//重新出现属性值表单元素的方法
const toEdit = (row: AttrValue, $index: number) => {
    row.flag = true
    //响应式数据发生变化，获取更新的组件实例
    nextTick(() => {
        inputArr.value[$index].focus()
    })
}
//删除某个已有属性的方法回调
const removeAttr = async (attrId: number) => {
    //发请求删除对应属性
    let result: any = await reqDeleteAttr(attrId)
    if (result.code == 200) {
        ElMessage({
            type: 'success',
            message: '删除成功'
        })
        //再次获取已有的属性数据
        getAttr()
    } else {
        ElMessage({
            type: 'error',
            message: '删除失败'
        })
    }
}

//监听仓库三级分类id的变化
watch(() => categoryStore.c3Id, () => {
    //清空上一次查询的属性与属性值
    attrArr.value = []
    if (!categoryStore.c3Id) {
        return
    }
    getAttr()
})
//路由组件销毁的时候，把仓库中对应分类相关的数据清空
onBeforeUnmount(() => {
    categoryStore.$reset()
})
</script>

<style scoped lang="scss"></style>